3 * Base representation for a MediaWiki page.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Abstract class for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
26 abstract class Page
{}
29 * Class representing a MediaWiki article and history.
31 * Some fields are public only for backwards-compatibility. Use accessors.
32 * In the past, this class was part of Article.php and everything was public.
34 * @internal documentation reviewed 15 Mar 2010
36 class WikiPage
extends Page
{
37 // doDeleteArticleReal() return values. Values less than zero indicate fatal errors,
38 // values greater than zero indicate that there were problems not resulting in page
42 * Delete operation aborted by hook
44 const DELETE_HOOK_ABORTED
= -1;
49 const DELETE_SUCCESS
= 0;
54 const DELETE_NO_PAGE
= 1;
57 * No revisions found to delete
59 const DELETE_NO_REVISIONS
= 2;
61 // Constants for $mDataLoadedFrom and related
64 * Data has not been loaded yet (or the object was cleared)
66 const DATA_NOT_LOADED
= 0;
69 * Data has been loaded from a slave database
71 const DATA_FROM_SLAVE
= 1;
74 * Data has been loaded from the master database
76 const DATA_FROM_MASTER
= 2;
79 * Data has been loaded from the master database using FOR UPDATE
81 const DATA_FOR_UPDATE
= 3;
86 public $mTitle = null;
91 public $mDataLoaded = false; // !< Boolean
92 public $mIsRedirect = false; // !< Boolean
93 public $mLatest = false; // !< Integer (false means "not loaded")
94 public $mPreparedEdit = false; // !< Array
98 * @var int; one of the DATA_* constants
100 protected $mDataLoadedFrom = self
::DATA_NOT_LOADED
;
105 protected $mRedirectTarget = null;
110 protected $mLastRevision = null;
113 * @var string; timestamp of the current revision or empty string if not loaded
115 protected $mTimestamp = '';
120 protected $mTouched = '19700101000000';
125 protected $mCounter = null;
128 * Constructor and clear the article
129 * @param $title Title Reference to a Title object.
131 public function __construct( Title
$title ) {
132 $this->mTitle
= $title;
136 * Create a WikiPage object of the appropriate class for the given title.
138 * @param $title Title
139 * @return WikiPage object of the appropriate type
141 public static function factory( Title
$title ) {
142 $ns = $title->getNamespace();
144 if ( $ns == NS_MEDIA
) {
145 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
146 } elseif ( $ns < 0 ) {
147 throw new MWException( "Invalid or virtual namespace $ns given." );
152 $page = new WikiFilePage( $title );
155 $page = new WikiCategoryPage( $title );
158 $page = new WikiPage( $title );
165 * Constructor from a page id
167 * @param $id Int article ID to load
168 * @param $from string|int one of the following values:
169 * - "fromdb" or self::DATA_FROM_SLAVE to select from a slave database
170 * - "fromdbmaster" or self::DATA_FROM_MASTER to select from the master database
172 * @return WikiPage|null
174 public static function newFromID( $id, $from = 'fromdb' ) {
175 $from = self
::convertSelectType( $from );
176 $db = wfGetDB( $from === self
::DATA_FROM_MASTER ? DB_MASTER
: DB_SLAVE
);
177 $row = $db->selectRow( 'page', self
::selectFields(), array( 'page_id' => $id ), __METHOD__
);
181 return self
::newFromRow( $row, $from );
185 * Constructor from a database row
188 * @param $row object: database row containing at least fields returned
190 * @param $from string|int: source of $data:
191 * - "fromdb" or self::DATA_FROM_SLAVE: from a slave DB
192 * - "fromdbmaster" or self::DATA_FROM_MASTER: from the master DB
193 * - "forupdate" or self::DATA_FOR_UPDATE: from the master DB using SELECT FOR UPDATE
196 public static function newFromRow( $row, $from = 'fromdb' ) {
197 $page = self
::factory( Title
::newFromRow( $row ) );
198 $page->loadFromRow( $row, $from );
203 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to DATA_* constants.
205 * @param $type object|string|int
208 private static function convertSelectType( $type ) {
211 return self
::DATA_FROM_SLAVE
;
213 return self
::DATA_FROM_MASTER
;
215 return self
::DATA_FOR_UPDATE
;
217 // It may already be an integer or whatever else
223 * Returns overrides for action handlers.
224 * Classes listed here will be used instead of the default one when
225 * (and only when) $wgActions[$action] === true. This allows subclasses
226 * to override the default behavior.
228 * @todo: move this UI stuff somewhere else
232 public function getActionOverrides() {
233 $content_handler = $this->getContentHandler();
234 return $content_handler->getActionOverrides();
238 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
240 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
242 * @return ContentHandler
246 public function getContentHandler() {
247 return ContentHandler
::getForModelID( $this->getContentModel() );
251 * Get the title object of the article
252 * @return Title object of this page
254 public function getTitle() {
255 return $this->mTitle
;
261 public function clear() {
262 $this->mDataLoaded
= false;
263 $this->mDataLoadedFrom
= self
::DATA_NOT_LOADED
;
265 $this->mCounter
= null;
266 $this->mRedirectTarget
= null; # Title object if set
267 $this->mLastRevision
= null; # Latest revision
268 $this->mTouched
= '19700101000000';
269 $this->mTimestamp
= '';
270 $this->mIsRedirect
= false;
271 $this->mLatest
= false;
272 $this->mPreparedEdit
= false;
276 * Return the list of revision fields that should be selected to create
281 public static function selectFields() {
282 global $wgContentHandlerUseDB;
298 if ( $wgContentHandlerUseDB ) {
299 $fields[] = 'page_content_model';
306 * Fetch a page record with the given conditions
307 * @param $dbr DatabaseBase object
308 * @param $conditions Array
309 * @param $options Array
310 * @return mixed Database result resource, or false on failure
312 protected function pageData( $dbr, $conditions, $options = array() ) {
313 $fields = self
::selectFields();
315 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
317 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
, $options );
319 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
325 * Fetch a page record matching the Title object's namespace and title
326 * using a sanitized title string
328 * @param $dbr DatabaseBase object
329 * @param $title Title object
330 * @param $options Array
331 * @return mixed Database result resource, or false on failure
333 public function pageDataFromTitle( $dbr, $title, $options = array() ) {
334 return $this->pageData( $dbr, array(
335 'page_namespace' => $title->getNamespace(),
336 'page_title' => $title->getDBkey() ), $options );
340 * Fetch a page record matching the requested ID
342 * @param $dbr DatabaseBase
344 * @param $options Array
345 * @return mixed Database result resource, or false on failure
347 public function pageDataFromId( $dbr, $id, $options = array() ) {
348 return $this->pageData( $dbr, array( 'page_id' => $id ), $options );
352 * Set the general counter, title etc data loaded from
355 * @param $from object|string|int One of the following:
356 * - A DB query result object
357 * - "fromdb" or self::DATA_FROM_SLAVE to get from a slave DB
358 * - "fromdbmaster" or self::DATA_FROM_MASTER to get from the master DB
359 * - "forupdate" or self::DATA_FOR_UPDATE to get from the master DB using SELECT FOR UPDATE
363 public function loadPageData( $from = 'fromdb' ) {
364 $from = self
::convertSelectType( $from );
365 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
366 // We already have the data from the correct location, no need to load it twice.
370 if ( $from === self
::DATA_FOR_UPDATE
) {
371 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
, array( 'FOR UPDATE' ) );
372 } elseif ( $from === self
::DATA_FROM_MASTER
) {
373 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
374 } elseif ( $from === self
::DATA_FROM_SLAVE
) {
375 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
376 # Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
377 # Note that DB also stores the master position in the session and checks it.
378 $touched = $this->getCachedLastEditTime();
379 if ( $touched ) { // key set
380 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
381 $from = self
::DATA_FROM_MASTER
;
382 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
386 // No idea from where the caller got this data, assume slave database.
388 $from = self
::DATA_FROM_SLAVE
;
391 $this->loadFromRow( $data, $from );
395 * Load the object from a database row
398 * @param $data object: database row containing at least fields returned
400 * @param $from string|int One of the following:
401 * - "fromdb" or self::DATA_FROM_SLAVE if the data comes from a slave DB
402 * - "fromdbmaster" or self::DATA_FROM_MASTER if the data comes from the master DB
403 * - "forupdate" or self::DATA_FOR_UPDATE if the data comes from from
404 * the master DB using SELECT FOR UPDATE
406 public function loadFromRow( $data, $from ) {
407 $lc = LinkCache
::singleton();
410 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
412 $this->mTitle
->loadFromRow( $data );
414 # Old-fashioned restrictions
415 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
417 $this->mCounter
= intval( $data->page_counter
);
418 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
419 $this->mIsRedirect
= intval( $data->page_is_redirect
);
420 $this->mLatest
= intval( $data->page_latest
);
422 $lc->addBadLinkObj( $this->mTitle
);
424 $this->mTitle
->loadFromRow( false );
427 $this->mDataLoaded
= true;
428 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
432 * @return int Page ID
434 public function getId() {
435 return $this->mTitle
->getArticleID();
439 * @return bool Whether or not the page exists in the database
441 public function exists() {
442 return $this->mTitle
->exists();
446 * Check if this page is something we're going to be showing
447 * some sort of sensible content for. If we return false, page
448 * views (plain action=view) will return an HTTP 404 response,
449 * so spiders and robots can know they're following a bad link.
453 public function hasViewableContent() {
454 return $this->mTitle
->exists() ||
$this->mTitle
->isAlwaysKnown();
458 * @return int The view count for the page
460 public function getCount() {
461 if ( !$this->mDataLoaded
) {
462 $this->loadPageData();
465 return $this->mCounter
;
469 * Tests if the article text represents a redirect
471 * @param $text mixed string containing article contents, or boolean
474 public function isRedirect( $text = false ) { #TODO: investiage whether we need the text param
475 if ( $text === false ) $content = $this->getContent();
476 else $content = ContentHandler
::makeContent( $text, $this->mTitle
); # TODO: allow model and format to be provided; or better, expect a Content object
479 if ( empty( $content ) ) return false;
480 else return $content->isRedirect();
484 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
486 * Will use the revisions actual content model if the page exists,
487 * and the page's default if the page doesn't exist yet.
493 public function getContentModel() {
494 if ( $this->exists() ) {
495 # look at the revision's actual content model
496 $rev = $this->getRevision();
498 if ( $rev !== null ) {
499 return $rev->getContentModel();
501 wfWarn( "Page exists but has no revision!" );
505 # use the default model for this page
506 return $this->mTitle
->getContentModel();
510 * Loads page_touched and returns a value indicating if it should be used
511 * @return boolean true if not a redirect
513 public function checkTouched() {
514 if ( !$this->mDataLoaded
) {
515 $this->loadPageData();
517 return !$this->mIsRedirect
;
521 * Get the page_touched field
522 * @return string containing GMT timestamp
524 public function getTouched() {
525 if ( !$this->mDataLoaded
) {
526 $this->loadPageData();
528 return $this->mTouched
;
532 * Get the page_latest field
533 * @return integer rev_id of current revision
535 public function getLatest() {
536 if ( !$this->mDataLoaded
) {
537 $this->loadPageData();
539 return (int)$this->mLatest
;
543 * Get the Revision object of the oldest revision
544 * @return Revision|null
546 public function getOldestRevision() {
547 wfProfileIn( __METHOD__
);
549 // Try using the slave database first, then try the master
551 $db = wfGetDB( DB_SLAVE
);
552 $revSelectFields = Revision
::selectFields();
554 while ( $continue ) {
555 $row = $db->selectRow(
556 array( 'page', 'revision' ),
559 'page_namespace' => $this->mTitle
->getNamespace(),
560 'page_title' => $this->mTitle
->getDBkey(),
565 'ORDER BY' => 'rev_timestamp ASC'
572 $db = wfGetDB( DB_MASTER
);
577 wfProfileOut( __METHOD__
);
578 return $row ? Revision
::newFromRow( $row ) : null;
582 * Loads everything except the text
583 * This isn't necessary for all uses, so it's only done if needed.
585 protected function loadLastEdit() {
586 if ( $this->mLastRevision
!== null ) {
587 return; // already loaded
590 $latest = $this->getLatest();
592 return; // page doesn't exist or is missing page_latest info
595 $revision = Revision
::newFromPageId( $this->getId(), $latest );
596 if ( $revision ) { // sanity
597 $this->setLastEdit( $revision );
602 * Set the latest revision
604 protected function setLastEdit( Revision
$revision ) {
605 $this->mLastRevision
= $revision;
606 $this->mTimestamp
= $revision->getTimestamp();
610 * Get the latest revision
611 * @return Revision|null
613 public function getRevision() {
614 $this->loadLastEdit();
615 if ( $this->mLastRevision
) {
616 return $this->mLastRevision
;
622 * Get the content of the current revision. No side-effects...
624 * @param $audience Integer: one of:
625 * Revision::FOR_PUBLIC to be displayed to all users
626 * Revision::FOR_THIS_USER to be displayed to $wgUser
627 * Revision::RAW get the text regardless of permissions
628 * @return Content|null The content of the current revision
632 public function getContent( $audience = Revision
::FOR_PUBLIC
) {
633 $this->loadLastEdit();
634 if ( $this->mLastRevision
) {
635 return $this->mLastRevision
->getContent( $audience );
641 * Get the text of the current revision. No side-effects...
643 * @param $audience Integer: one of:
644 * Revision::FOR_PUBLIC to be displayed to all users
645 * Revision::FOR_THIS_USER to be displayed to $wgUser
646 * Revision::RAW get the text regardless of permissions
647 * @return String|false The text of the current revision
648 * @deprecated as of 1.WD, getContent() should be used instead.
650 public function getText( $audience = Revision
::FOR_PUBLIC
) { #@todo: deprecated, replace usage!
651 wfDeprecated( __METHOD__
, '1.WD' );
653 $this->loadLastEdit();
654 if ( $this->mLastRevision
) {
655 return $this->mLastRevision
->getText( $audience );
661 * Get the text of the current revision. No side-effects...
663 * @return String|bool The text of the current revision. False on failure
664 * @deprecated as of 1.WD, getContent() should be used instead.
666 public function getRawText() { #@todo: deprecated, replace usage!
667 wfDeprecated( __METHOD__
, '1.WD' );
669 return $this->getText( Revision
::RAW
);
673 * @return string MW timestamp of last article revision
675 public function getTimestamp() {
676 // Check if the field has been filled by WikiPage::setTimestamp()
677 if ( !$this->mTimestamp
) {
678 $this->loadLastEdit();
681 return wfTimestamp( TS_MW
, $this->mTimestamp
);
685 * Set the page timestamp (use only to avoid DB queries)
686 * @param $ts string MW timestamp of last article revision
689 public function setTimestamp( $ts ) {
690 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
694 * @param $audience Integer: one of:
695 * Revision::FOR_PUBLIC to be displayed to all users
696 * Revision::FOR_THIS_USER to be displayed to $wgUser
697 * Revision::RAW get the text regardless of permissions
698 * @return int user ID for the user that made the last article revision
700 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
701 $this->loadLastEdit();
702 if ( $this->mLastRevision
) {
703 return $this->mLastRevision
->getUser( $audience );
710 * Get the User object of the user who created the page
711 * @param $audience Integer: one of:
712 * Revision::FOR_PUBLIC to be displayed to all users
713 * Revision::FOR_THIS_USER to be displayed to $wgUser
714 * Revision::RAW get the text regardless of permissions
717 public function getCreator( $audience = Revision
::FOR_PUBLIC
) {
718 $revision = $this->getOldestRevision();
720 $userName = $revision->getUserText( $audience );
721 return User
::newFromName( $userName, false );
728 * @param $audience Integer: one of:
729 * Revision::FOR_PUBLIC to be displayed to all users
730 * Revision::FOR_THIS_USER to be displayed to $wgUser
731 * Revision::RAW get the text regardless of permissions
732 * @return string username of the user that made the last article revision
734 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
735 $this->loadLastEdit();
736 if ( $this->mLastRevision
) {
737 return $this->mLastRevision
->getUserText( $audience );
744 * @param $audience Integer: one of:
745 * Revision::FOR_PUBLIC to be displayed to all users
746 * Revision::FOR_THIS_USER to be displayed to $wgUser
747 * Revision::RAW get the text regardless of permissions
748 * @return string Comment stored for the last article revision
750 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
751 $this->loadLastEdit();
752 if ( $this->mLastRevision
) {
753 return $this->mLastRevision
->getComment( $audience );
760 * Returns true if last revision was marked as "minor edit"
762 * @return boolean Minor edit indicator for the last article revision.
764 public function getMinorEdit() {
765 $this->loadLastEdit();
766 if ( $this->mLastRevision
) {
767 return $this->mLastRevision
->isMinor();
774 * Get the cached timestamp for the last time the page changed.
775 * This is only used to help handle slave lag by comparing to page_touched.
776 * @return string MW timestamp
778 protected function getCachedLastEditTime() {
780 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
781 return $wgMemc->get( $key );
785 * Set the cached timestamp for the last time the page changed.
786 * This is only used to help handle slave lag by comparing to page_touched.
787 * @param $timestamp string
790 public function setCachedLastEditTime( $timestamp ) {
792 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
793 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
797 * Determine whether a page would be suitable for being counted as an
798 * article in the site_stats table based on the title & its content
800 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
801 * if false, the current database state will be used
804 public function isCountable( $editInfo = false ) {
805 global $wgArticleCountMethod;
807 if ( !$this->mTitle
->isContentPage() ) {
812 $content = $editInfo->pstContent
;
814 $content = $this->getContent();
817 if ( !$content ||
$content->isRedirect( ) ) {
823 if ( $wgArticleCountMethod === 'link' ) {
824 # nasty special case to avoid re-parsing to detect links
827 // ParserOutput::getLinks() is a 2D array of page links, so
828 // to be really correct we would need to recurse in the array
829 // but the main array should only have items in it if there are
831 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
833 $hasLinks = (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
834 array( 'pl_from' => $this->getId() ), __METHOD__
);
838 return $content->isCountable( $hasLinks );
842 * If this page is a redirect, get its target
844 * The target will be fetched from the redirect table if possible.
845 * If this page doesn't have an entry there, call insertRedirect()
846 * @return Title|mixed object, or null if this page is not a redirect
848 public function getRedirectTarget() {
849 if ( !$this->mTitle
->isRedirect() ) {
853 if ( $this->mRedirectTarget
!== null ) {
854 return $this->mRedirectTarget
;
857 # Query the redirect table
858 $dbr = wfGetDB( DB_SLAVE
);
859 $row = $dbr->selectRow( 'redirect',
860 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
861 array( 'rd_from' => $this->getId() ),
865 // rd_fragment and rd_interwiki were added later, populate them if empty
866 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
867 return $this->mRedirectTarget
= Title
::makeTitle(
868 $row->rd_namespace
, $row->rd_title
,
869 $row->rd_fragment
, $row->rd_interwiki
);
872 # This page doesn't have an entry in the redirect table
873 return $this->mRedirectTarget
= $this->insertRedirect();
877 * Insert an entry for this page into the redirect table.
879 * Don't call this function directly unless you know what you're doing.
880 * @return Title object or null if not a redirect
882 public function insertRedirect() {
883 // recurse through to only get the final target
884 $content = $this->getContent();
885 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
889 $this->insertRedirectEntry( $retval );
894 * Insert or update the redirect table entry for this page to indicate
895 * it redirects to $rt .
896 * @param $rt Title redirect target
898 public function insertRedirectEntry( $rt ) {
899 $dbw = wfGetDB( DB_MASTER
);
900 $dbw->replace( 'redirect', array( 'rd_from' ),
902 'rd_from' => $this->getId(),
903 'rd_namespace' => $rt->getNamespace(),
904 'rd_title' => $rt->getDBkey(),
905 'rd_fragment' => $rt->getFragment(),
906 'rd_interwiki' => $rt->getInterwiki(),
913 * Get the Title object or URL this page redirects to
915 * @return mixed false, Title of in-wiki target, or string with URL
917 public function followRedirect() {
918 return $this->getRedirectURL( $this->getRedirectTarget() );
922 * Get the Title object or URL to use for a redirect. We use Title
923 * objects for same-wiki, non-special redirects and URLs for everything
925 * @param $rt Title Redirect target
926 * @return mixed false, Title object of local target, or string with URL
928 public function getRedirectURL( $rt ) {
933 if ( $rt->isExternal() ) {
934 if ( $rt->isLocal() ) {
935 // Offsite wikis need an HTTP redirect.
937 // This can be hard to reverse and may produce loops,
938 // so they may be disabled in the site configuration.
939 $source = $this->mTitle
->getFullURL( 'redirect=no' );
940 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
942 // External pages pages without "local" bit set are not valid
948 if ( $rt->isSpecialPage() ) {
949 // Gotta handle redirects to special pages differently:
950 // Fill the HTTP response "Location" header and ignore
951 // the rest of the page we're on.
953 // Some pages are not valid targets
954 if ( $rt->isValidRedirectTarget() ) {
955 return $rt->getFullURL();
965 * Get a list of users who have edited this article, not including the user who made
966 * the most recent revision, which you can get from $article->getUser() if you want it
967 * @return UserArrayFromResult
969 public function getContributors() {
970 # @todo FIXME: This is expensive; cache this info somewhere.
972 $dbr = wfGetDB( DB_SLAVE
);
974 if ( $dbr->implicitGroupby() ) {
975 $realNameField = 'user_real_name';
977 $realNameField = 'MIN(user_real_name) AS user_real_name';
980 $tables = array( 'revision', 'user' );
983 'rev_user as user_id',
984 'rev_user_text AS user_name',
986 'MAX(rev_timestamp) AS timestamp',
989 $conds = array( 'rev_page' => $this->getId() );
991 // The user who made the top revision gets credited as "this page was last edited by
992 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
993 $user = $this->getUser();
995 $conds[] = "rev_user != $user";
997 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1000 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
1003 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
1007 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
1008 'ORDER BY' => 'timestamp DESC',
1011 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1012 return new UserArrayFromResult( $res );
1016 * Get the last N authors
1017 * @param $num Integer: number of revisions to get
1018 * @param $revLatest String: the latest rev_id, selected from the master (optional)
1019 * @return array Array of authors, duplicates not removed
1021 public function getLastNAuthors( $num, $revLatest = 0 ) {
1022 wfProfileIn( __METHOD__
);
1023 // First try the slave
1024 // If that doesn't have the latest revision, try the master
1026 $db = wfGetDB( DB_SLAVE
);
1029 $res = $db->select( array( 'page', 'revision' ),
1030 array( 'rev_id', 'rev_user_text' ),
1032 'page_namespace' => $this->mTitle
->getNamespace(),
1033 'page_title' => $this->mTitle
->getDBkey(),
1034 'rev_page = page_id'
1037 'ORDER BY' => 'rev_timestamp DESC',
1043 wfProfileOut( __METHOD__
);
1047 $row = $db->fetchObject( $res );
1049 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1050 $db = wfGetDB( DB_MASTER
);
1055 } while ( $continue );
1057 $authors = array( $row->rev_user_text
);
1059 foreach ( $res as $row ) {
1060 $authors[] = $row->rev_user_text
;
1063 wfProfileOut( __METHOD__
);
1068 * Should the parser cache be used?
1070 * @param $parserOptions ParserOptions to check
1074 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
1075 global $wgEnableParserCache;
1077 return $wgEnableParserCache
1078 && $parserOptions->getStubThreshold() == 0
1079 && $this->mTitle
->exists()
1080 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
1081 && $this->getContentHandler()->isParserCacheSupported();
1085 * Get a ParserOutput for the given ParserOptions and revision ID.
1086 * The parser cache will be used if possible.
1089 * @param $parserOptions ParserOptions to use for the parse operation
1090 * @param $oldid Revision ID to get the text from, passing null or 0 will
1091 * get the current revision (default value)
1093 * @return ParserOutput or false if the revision was not found
1095 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
1096 wfProfileIn( __METHOD__
);
1098 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
1099 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1100 if ( $parserOptions->getStubThreshold() ) {
1101 wfIncrStats( 'pcache_miss_stub' );
1104 if ( $useParserCache ) {
1105 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
1106 if ( $parserOutput !== false ) {
1107 wfProfileOut( __METHOD__
);
1108 return $parserOutput;
1112 if ( $oldid === null ||
$oldid === 0 ) {
1113 $oldid = $this->getLatest();
1116 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1119 wfProfileOut( __METHOD__
);
1121 return $pool->getParserOutput();
1125 * Do standard deferred updates after page view
1126 * @param $user User The relevant user
1128 public function doViewUpdates( User
$user ) {
1129 global $wgDisableCounters;
1130 if ( wfReadOnly() ) {
1134 # Don't update page view counters on views from bot users (bug 14044)
1135 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle
->exists() ) {
1136 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
1137 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
1140 # Update newtalk / watchlist notification status
1141 $user->clearNotification( $this->mTitle
);
1145 * Perform the actions of a page purging
1148 public function doPurge() {
1151 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
1155 // Invalidate the cache
1156 $this->mTitle
->invalidateCache();
1159 if ( $wgUseSquid ) {
1160 // Commit the transaction before the purge is sent
1161 $dbw = wfGetDB( DB_MASTER
);
1162 $dbw->commit( __METHOD__
);
1165 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1166 $update->doUpdate();
1169 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1170 if ( $this->mTitle
->exists() ) {
1171 $text = ContentHandler
::getContentText( $this->getContent() ); #XXX: get native data directly?
1176 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1182 * Insert a new empty page record for this article.
1183 * This *must* be followed up by creating a revision
1184 * and running $this->updateRevisionOn( ... );
1185 * or else the record will be left in a funky state.
1186 * Best if all done inside a transaction.
1188 * @param $dbw DatabaseBase
1189 * @return int The newly created page_id key, or false if the title already existed
1191 public function insertOn( $dbw ) {
1192 wfProfileIn( __METHOD__
);
1194 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1195 $dbw->insert( 'page', array(
1196 'page_id' => $page_id,
1197 'page_namespace' => $this->mTitle
->getNamespace(),
1198 'page_title' => $this->mTitle
->getDBkey(),
1199 'page_counter' => 0,
1200 'page_restrictions' => '',
1201 'page_is_redirect' => 0, # Will set this shortly...
1203 'page_random' => wfRandom(),
1204 'page_touched' => $dbw->timestamp(),
1205 'page_latest' => 0, # Fill this in shortly...
1206 'page_len' => 0, # Fill this in shortly...
1207 ), __METHOD__
, 'IGNORE' );
1209 $affected = $dbw->affectedRows();
1212 $newid = $dbw->insertId();
1213 $this->mTitle
->resetArticleID( $newid );
1215 wfProfileOut( __METHOD__
);
1217 return $affected ?
$newid : false;
1221 * Update the page record to point to a newly saved revision.
1223 * @param $dbw DatabaseBase: object
1224 * @param $revision Revision: For ID number, and text used to set
1225 * length and redirect status fields
1226 * @param $lastRevision Integer: if given, will not overwrite the page field
1227 * when different from the currently set value.
1228 * Giving 0 indicates the new page flag should be set
1230 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1231 * removing rows in redirect table.
1232 * @return bool true on success, false on failure
1235 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1236 global $wgContentHandlerUseDB;
1238 wfProfileIn( __METHOD__
);
1240 $content = $revision->getContent();
1241 $len = $content->getSize();
1242 $rt = $content->getUltimateRedirectTarget();
1244 $conditions = array( 'page_id' => $this->getId() );
1246 if ( !is_null( $lastRevision ) ) {
1247 # An extra check against threads stepping on each other
1248 $conditions['page_latest'] = $lastRevision;
1251 $now = wfTimestampNow();
1252 $row = array( /* SET */
1253 'page_latest' => $revision->getId(),
1254 'page_touched' => $dbw->timestamp( $now ),
1255 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1256 'page_is_redirect' => $rt !== null ?
1 : 0,
1260 if ( $wgContentHandlerUseDB ) {
1261 $row[ 'page_content_model' ] = $revision->getContentModel();
1264 $dbw->update( 'page',
1269 $result = $dbw->affectedRows() != 0;
1271 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1272 $this->setLastEdit( $revision );
1273 $this->setCachedLastEditTime( $now );
1274 $this->mLatest
= $revision->getId();
1275 $this->mIsRedirect
= (bool)$rt;
1276 # Update the LinkCache.
1277 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
, $this->mLatest
);
1280 wfProfileOut( __METHOD__
);
1285 * Add row to the redirect table if this is a redirect, remove otherwise.
1287 * @param $dbw DatabaseBase
1288 * @param $redirectTitle Title object pointing to the redirect target,
1289 * or NULL if this is not a redirect
1290 * @param $lastRevIsRedirect null|bool If given, will optimize adding and
1291 * removing rows in redirect table.
1292 * @return bool true on success, false on failure
1295 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1296 // Always update redirects (target link might have changed)
1297 // Update/Insert if we don't know if the last revision was a redirect or not
1298 // Delete if changing from redirect to non-redirect
1299 $isRedirect = !is_null( $redirectTitle );
1301 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1305 wfProfileIn( __METHOD__
);
1306 if ( $isRedirect ) {
1307 $this->insertRedirectEntry( $redirectTitle );
1309 // This is not a redirect, remove row from redirect table
1310 $where = array( 'rd_from' => $this->getId() );
1311 $dbw->delete( 'redirect', $where, __METHOD__
);
1314 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1315 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1317 wfProfileOut( __METHOD__
);
1319 return ( $dbw->affectedRows() != 0 );
1323 * If the given revision is newer than the currently set page_latest,
1324 * update the page record. Otherwise, do nothing.
1326 * @param $dbw DatabaseBase object
1327 * @param $revision Revision object
1330 public function updateIfNewerOn( $dbw, $revision ) {
1331 wfProfileIn( __METHOD__
);
1333 $row = $dbw->selectRow(
1334 array( 'revision', 'page' ),
1335 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1337 'page_id' => $this->getId(),
1338 'page_latest=rev_id' ),
1342 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1343 wfProfileOut( __METHOD__
);
1346 $prev = $row->rev_id
;
1347 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1349 # No or missing previous revision; mark the page as new
1351 $lastRevIsRedirect = null;
1354 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1356 wfProfileOut( __METHOD__
);
1361 * Get the text that needs to be saved in order to undo all revisions
1362 * between $undo and $undoafter. Revisions must belong to the same page,
1363 * must exist and must not be deleted
1364 * @param $undo Revision
1365 * @param $undoafter Revision Must be an earlier revision than $undo
1366 * @return mixed string on success, false on failure
1367 * @deprecated since 1.WD: use ContentHandler::getUndoContent() instead.
1369 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
1370 wfDeprecated( __METHOD__
, '1.WD' );
1372 $this->loadLastEdit();
1374 if ( $this->mLastRevision
) {
1375 if ( is_null( $undoafter ) ) {
1376 $undoafter = $undo->getPrevious();
1379 $handler = $this->getContentHandler();
1380 $undone = $handler->getUndoContent( $this->mLastRevision
, $undo, $undoafter );
1385 return ContentHandler
::getContentText( $undone );
1393 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1394 * @param $text String: new text of the section
1395 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1396 * @param $edittime String: revision timestamp or null to use the current revision
1397 * @return String new complete article text, or null if error
1399 * @deprecated since 1.WD, use replaceSectionContent() instead
1401 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1402 wfDeprecated( __METHOD__
, '1.WD' );
1404 $sectionContent = ContentHandler
::makeContent( $text, $this->getTitle() ); #XXX: could make section title, but that's not required.
1406 $newContent = $this->replaceSectionContent( $section, $sectionContent, $sectionTitle, $edittime );
1407 #TODO: check $newContent == false. throw exception??
1408 #TODO: add ContentHandler::supportsSections()
1410 return ContentHandler
::getContentText( $newContent ); #XXX: unclear what will happen for non-wikitext!
1414 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1415 * @param $content Content: new content of the section
1416 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1417 * @param $edittime String: revision timestamp or null to use the current revision
1419 * @return Content new complete article content, or null if error
1423 public function replaceSectionContent( $section, Content
$sectionContent, $sectionTitle = '', $edittime = null ) {
1424 wfProfileIn( __METHOD__
);
1426 if ( strval( $section ) == '' ) {
1427 // Whole-page edit; let the whole text through
1428 $newContent = $sectionContent;
1430 // Bug 30711: always use current version when adding a new section
1431 if ( is_null( $edittime ) ||
$section == 'new' ) {
1432 $oldContent = $this->getContent();
1433 if ( ! $oldContent ) {
1434 wfDebug( __METHOD__
. ": no page text\n" );
1435 wfProfileOut( __METHOD__
);
1439 $dbw = wfGetDB( DB_MASTER
);
1440 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1443 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1444 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1445 wfProfileOut( __METHOD__
);
1449 $oldContent = $rev->getContent();
1452 $newContent = $oldContent->replaceSection( $section, $sectionContent, $sectionTitle );
1455 wfProfileOut( __METHOD__
);
1460 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1462 * @return Int updated $flags
1464 function checkFlags( $flags ) {
1465 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1466 if ( $this->mTitle
->getArticleID() ) {
1467 $flags |
= EDIT_UPDATE
;
1477 * Change an existing article or create a new article. Updates RC and all necessary caches,
1478 * optionally via the deferred update array.
1480 * @param $text String: new text
1481 * @param $summary String: edit summary
1482 * @param $flags Integer bitfield:
1484 * Article is known or assumed to be non-existent, create a new one
1486 * Article is known or assumed to be pre-existing, update it
1488 * Mark this edit minor, if the user is allowed to do so
1490 * Do not log the change in recentchanges
1492 * Mark the edit a "bot" edit regardless of user rights
1493 * EDIT_DEFER_UPDATES
1494 * Defer some of the updates until the end of index.php
1496 * Fill in blank summaries with generated text where possible
1498 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1499 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1500 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1501 * edit-already-exists error will be returned. These two conditions are also possible with
1502 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1504 * @param $baseRevId int the revision ID this edit was based off, if any
1505 * @param $user User the user doing the edit
1507 * @return Status object. Possible errors:
1508 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1509 * edit-gone-missing: In update mode, but the article didn't exist
1510 * edit-conflict: In update mode, the article changed unexpectedly
1511 * edit-no-change: Warning that the text was the same as before
1512 * edit-already-exists: In creation mode, but the article already exists
1514 * Extensions may define additional errors.
1516 * $return->value will contain an associative array with members as follows:
1517 * new: Boolean indicating if the function attempted to create a new article
1518 * revision: The revision object for the inserted revision, or null
1520 * Compatibility note: this function previously returned a boolean value indicating success/failure
1522 * @deprecated since 1.WD: use doEditContent() instead.
1524 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) { #@todo: use doEditContent() instead
1525 wfDeprecated( __METHOD__
, '1.WD' );
1527 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1529 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1533 * Change an existing article or create a new article. Updates RC and all necessary caches,
1534 * optionally via the deferred update array.
1536 * @param $content Content: new content
1537 * @param $summary String: edit summary
1538 * @param $flags Integer bitfield:
1540 * Article is known or assumed to be non-existent, create a new one
1542 * Article is known or assumed to be pre-existing, update it
1544 * Mark this edit minor, if the user is allowed to do so
1546 * Do not log the change in recentchanges
1548 * Mark the edit a "bot" edit regardless of user rights
1549 * EDIT_DEFER_UPDATES
1550 * Defer some of the updates until the end of index.php
1552 * Fill in blank summaries with generated text where possible
1554 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1555 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1556 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1557 * edit-already-exists error will be returned. These two conditions are also possible with
1558 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1560 * @param $baseRevId the revision ID this edit was based off, if any
1561 * @param $user User the user doing the edit
1562 * @param $serialisation_format String: format for storing the content in the database
1564 * @return Status object. Possible errors:
1565 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1566 * edit-gone-missing: In update mode, but the article didn't exist
1567 * edit-conflict: In update mode, the article changed unexpectedly
1568 * edit-no-change: Warning that the text was the same as before
1569 * edit-already-exists: In creation mode, but the article already exists
1571 * Extensions may define additional errors.
1573 * $return->value will contain an associative array with members as follows:
1574 * new: Boolean indicating if the function attempted to create a new article
1575 * revision: The revision object for the inserted revision, or null
1579 public function doEditContent( Content
$content, $summary, $flags = 0, $baseRevId = false,
1580 User
$user = null, $serialisation_format = null ) {
1581 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1583 # Low-level sanity check
1584 if ( $this->mTitle
->getText() === '' ) {
1585 throw new MWException( 'Something is trying to edit an article with an empty title' );
1588 wfProfileIn( __METHOD__
);
1590 $user = is_null( $user ) ?
$wgUser : $user;
1591 $status = Status
::newGood( array() );
1593 // Load the data from the master database if needed.
1594 // The caller may already loaded it from the master or even loaded it using
1595 // SELECT FOR UPDATE, so do not override that using clear().
1596 $this->loadPageData( 'fromdbmaster' );
1598 $flags = $this->checkFlags( $flags );
1601 $hook_ok = wfRunHooks( 'ArticleContentSave', array( &$this, &$user, &$content, &$summary,
1602 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) );
1604 if ( $hook_ok && !empty( $wgHooks['ArticleSave'] ) ) { #FIXME: use wfHasHook or whatever. # avoid serialization overhead if the hook isn't present
1605 $content_text = $content->serialize();
1606 $txt = $content_text; # clone
1608 $hook_ok = wfRunHooks( 'ArticleSave', array( &$this, &$user, &$txt, &$summary,
1609 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ); #TODO: survey extensions using this hook
1611 if ( $txt !== $content_text ) {
1612 # if the text changed, unserialize the new version to create an updated Content object.
1613 $content = $content->getContentHandler()->unserializeContent( $txt );
1618 wfDebug( __METHOD__
. ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1620 if ( $status->isOK() ) {
1621 $status->fatal( 'edit-hook-aborted' );
1624 wfProfileOut( __METHOD__
);
1628 # Silently ignore EDIT_MINOR if not allowed
1629 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1630 $bot = $flags & EDIT_FORCE_BOT
;
1632 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1634 $oldsize = $old_content ?
$old_content->getSize() : 0;
1635 $oldid = $this->getLatest();
1636 $oldIsRedirect = $this->isRedirect();
1637 $oldcountable = $this->isCountable();
1639 $handler = $content->getContentHandler();
1641 # Provide autosummaries if one is not provided and autosummaries are enabled.
1642 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1643 if ( !$old_content ) $old_content = null;
1644 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1647 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialisation_format );
1648 $serialized = $editInfo->pst
;
1649 $content = $editInfo->pstContent
;
1650 $newsize = $content->getSize();
1652 $dbw = wfGetDB( DB_MASTER
);
1653 $now = wfTimestampNow();
1654 $this->mTimestamp
= $now;
1656 if ( $flags & EDIT_UPDATE
) {
1657 # Update article, but only if changed.
1658 $status->value
['new'] = false;
1661 # Article gone missing
1662 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1663 $status->fatal( 'edit-gone-missing' );
1665 wfProfileOut( __METHOD__
);
1669 # Make sure the revision is either completely inserted or not inserted at all
1670 if ( !$wgDBtransactions ) {
1671 $userAbort = ignore_user_abort( true );
1674 $revision = new Revision( array(
1675 'page' => $this->getId(),
1676 'comment' => $summary,
1677 'minor_edit' => $isminor,
1678 'text' => $serialized,
1680 'parent_id' => $oldid,
1681 'user' => $user->getId(),
1682 'user_text' => $user->getName(),
1683 'timestamp' => $now,
1684 'content_model' => $content->getModel(),
1685 'content_format' => $serialisation_format,
1686 ) ); #XXX: pass content object?!
1688 $changed = !$content->equals( $old_content );
1692 if ( $content->isValid() ) {
1693 #XXX: do it! throw exception??
1696 $dbw->begin( __METHOD__
);
1697 $revisionId = $revision->insertOn( $dbw );
1701 # Note that we use $this->mLatest instead of fetching a value from the master DB
1702 # during the course of this function. This makes sure that EditPage can detect
1703 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1704 # before this function is called. A previous function used a separate query, this
1705 # creates a window where concurrent edits can cause an ignored edit conflict.
1706 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1709 /* Belated edit conflict! Run away!! */
1710 $status->fatal( 'edit-conflict' );
1712 # Delete the invalid revision if the DB is not transactional
1713 if ( !$wgDBtransactions ) {
1714 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__
);
1718 $dbw->rollback( __METHOD__
);
1720 global $wgUseRCPatrol;
1721 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1722 # Update recentchanges
1723 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1724 # Mark as patrolled if the user can do so
1725 $patrolled = $wgUseRCPatrol && !count(
1726 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1727 # Add RC row to the DB
1728 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1729 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1730 $revisionId, $patrolled
1733 # Log auto-patrolled edits
1735 PatrolLog
::record( $rc, true, $user );
1738 $user->incEditCount();
1739 $dbw->commit( __METHOD__
);
1742 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1743 // related variables correctly
1744 $revision->setId( $this->getLatest() );
1747 if ( !$wgDBtransactions ) {
1748 ignore_user_abort( $userAbort );
1751 // Now that ignore_user_abort is restored, we can respond to fatal errors
1752 if ( !$status->isOK() ) {
1753 wfProfileOut( __METHOD__
);
1757 # Update links tables, site stats, etc.
1758 $this->doEditUpdates(
1762 'changed' => $changed,
1763 'oldcountable' => $oldcountable
1768 $status->warning( 'edit-no-change' );
1770 // Update page_touched, this is usually implicit in the page update
1771 // Other cache updates are done in onArticleEdit()
1772 $this->mTitle
->invalidateCache();
1775 # Create new article
1776 $status->value
['new'] = true;
1778 $dbw->begin( __METHOD__
);
1780 # Add the page record; stake our claim on this title!
1781 # This will return false if the article already exists
1782 $newid = $this->insertOn( $dbw );
1784 if ( $newid === false ) {
1785 $dbw->rollback( __METHOD__
);
1786 $status->fatal( 'edit-already-exists' );
1788 wfProfileOut( __METHOD__
);
1792 # Save the revision text...
1793 $revision = new Revision( array(
1795 'comment' => $summary,
1796 'minor_edit' => $isminor,
1797 'text' => $serialized,
1799 'user' => $user->getId(),
1800 'user_text' => $user->getName(),
1801 'timestamp' => $now,
1802 'content_model' => $content->getModel(),
1803 'content_format' => $serialisation_format,
1805 $revisionId = $revision->insertOn( $dbw );
1807 # Update the page record with revision data
1808 $this->updateRevisionOn( $dbw, $revision, 0 );
1810 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1812 # Update recentchanges
1813 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1814 global $wgUseRCPatrol, $wgUseNPPatrol;
1816 # Mark as patrolled if the user can do so
1817 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1818 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1819 # Add RC row to the DB
1820 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1821 '', $content->getSize(), $revisionId, $patrolled );
1823 # Log auto-patrolled edits
1825 PatrolLog
::record( $rc, true, $user );
1828 $user->incEditCount();
1829 $dbw->commit( __METHOD__
);
1831 # Update links, etc.
1832 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1834 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $serialized, $summary,
1835 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1837 wfRunHooks( 'ArticleContentInsertComplete', array( &$this, &$user, $content, $summary,
1838 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1841 # Do updates right now unless deferral was requested
1842 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1843 DeferredUpdates
::doUpdates();
1846 // Return the new revision (or null) to the caller
1847 $status->value
['revision'] = $revision;
1849 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $serialized, $summary,
1850 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1852 wfRunHooks( 'ArticleContentSaveComplete', array( &$this, &$user, $content, $summary,
1853 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1855 # Promote user to any groups they meet the criteria for
1856 $user->addAutopromoteOnceGroups( 'onEdit' );
1858 wfProfileOut( __METHOD__
);
1863 * Get parser options suitable for rendering the primary article wikitext
1864 * @param User|string $user User object or 'canonical'
1865 * @return ParserOptions
1867 public function makeParserOptions( $user ) {
1869 if ( $user instanceof User
) { // settings per user (even anons)
1870 $options = ParserOptions
::newFromUser( $user );
1871 } else { // canonical settings
1872 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1874 $options->enableLimitReport(); // show inclusion/loop reports
1875 $options->setTidy( true ); // fix bad HTML
1880 * Prepare text which is about to be saved.
1881 * Returns a stdclass with source, pst and output members
1883 * @deprecated in 1.WD: use prepareContentForEdit instead.
1885 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1886 wfDeprecated( __METHOD__
, '1.WD' );
1887 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1888 return $this->prepareContentForEdit( $content, $revid , $user );
1892 * Prepare content which is about to be saved.
1893 * Returns a stdclass with source, pst and output members
1895 * @param \Content $content
1896 * @param null $revid
1897 * @param null|\User $user
1898 * @param null $serialization_format
1900 * @return bool|object
1904 public function prepareContentForEdit( Content
$content, $revid = null, User
$user = null, $serialization_format = null ) {
1905 global $wgParser, $wgContLang, $wgUser;
1906 $user = is_null( $user ) ?
$wgUser : $user;
1907 // @TODO fixme: check $user->getId() here???
1909 if ( $this->mPreparedEdit
1910 && $this->mPreparedEdit
->newContent
1911 && $this->mPreparedEdit
->newContent
->equals( $content )
1912 && $this->mPreparedEdit
->revid
== $revid
1913 && $this->mPreparedEdit
->format
== $serialization_format
1914 #XXX: also check $user here?
1917 return $this->mPreparedEdit
;
1920 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1921 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1923 $edit = (object)array();
1924 $edit->revid
= $revid;
1926 $edit->pstContent
= $content->preSaveTransform( $this->mTitle
, $user, $popts );
1927 $edit->pst
= $edit->pstContent
->serialize( $serialization_format ); #XXX: do we need this??
1928 $edit->format
= $serialization_format;
1930 $edit->popts
= $this->makeParserOptions( 'canonical' );
1932 $edit->output
= $edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
);
1934 $edit->newContent
= $content;
1935 $edit->oldContent
= $this->getContent( Revision
::RAW
);
1937 $edit->newText
= ContentHandler
::getContentText( $edit->newContent
); #FIXME: B/C only! don't use this field!
1938 $edit->oldText
= $edit->oldContent ? ContentHandler
::getContentText( $edit->oldContent
) : ''; #FIXME: B/C only! don't use this field!
1940 $this->mPreparedEdit
= $edit;
1946 * Do standard deferred updates after page edit.
1947 * Update links tables, site stats, search index and message cache.
1948 * Purges pages that include this page if the text was changed here.
1949 * Every 100th edit, prune the recent changes table.
1951 * @param $revision Revision object
1952 * @param $user User object that did the revision
1953 * @param $options Array of options, following indexes are used:
1954 * - changed: boolean, whether the revision changed the content (default true)
1955 * - created: boolean, whether the revision created the page (default false)
1956 * - oldcountable: boolean or null (default null):
1957 * - boolean: whether the page was counted as an article before that
1958 * revision, only used in changed is true and created is false
1959 * - null: don't change the article count
1961 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1962 global $wgEnableParserCache;
1964 wfProfileIn( __METHOD__
);
1966 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1967 $content = $revision->getContent();
1970 # Be careful not to double-PST: $text is usually already PST-ed once
1971 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1972 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1973 $editInfo = $this->prepareContentForEdit( $content, $revision->getId(), $user );
1975 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1976 $editInfo = $this->mPreparedEdit
;
1979 # Save it to the parser cache
1980 if ( $wgEnableParserCache ) {
1981 $parserCache = ParserCache
::singleton();
1982 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1985 # Update the links tables and other secondary data
1986 $contentHandler = $revision->getContentHandler();
1987 $updates = $contentHandler->getSecondaryDataUpdates( $content, $this->getTitle(), null, true, $editInfo->output
);
1988 DataUpdate
::runUpdates( $updates );
1990 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1992 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1993 if ( 0 == mt_rand( 0, 99 ) ) {
1994 // Flush old entries from the `recentchanges` table; we do this on
1995 // random requests so as to avoid an increase in writes for no good reason
1998 $dbw = wfGetDB( DB_MASTER
);
1999 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2002 array( "rc_timestamp < '$cutoff'" ),
2008 if ( !$this->mTitle
->exists() ) {
2009 wfProfileOut( __METHOD__
);
2013 $id = $this->getId();
2014 $title = $this->mTitle
->getPrefixedDBkey();
2015 $shortTitle = $this->mTitle
->getDBkey();
2017 if ( !$options['changed'] ) {
2020 } elseif ( $options['created'] ) {
2021 $good = (int)$this->isCountable( $editInfo );
2023 } elseif ( $options['oldcountable'] !== null ) {
2024 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2031 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
2032 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content->getTextForSearchIndex() ) ); #TODO: let the search engine decide what to do with the content object
2034 # If this is another user's talk page, update newtalk.
2035 # Don't do this if $options['changed'] = false (null-edits) nor if
2036 # it's a minor edit and the user doesn't want notifications for those.
2037 if ( $options['changed']
2038 && $this->mTitle
->getNamespace() == NS_USER_TALK
2039 && $shortTitle != $user->getTitleKey()
2040 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2042 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
2043 $other = User
::newFromName( $shortTitle, false );
2045 wfDebug( __METHOD__
. ": invalid username\n" );
2046 } elseif ( User
::isIP( $shortTitle ) ) {
2047 // An anonymous user
2048 $other->setNewtalk( true );
2049 } elseif ( $other->isLoggedIn() ) {
2050 $other->setNewtalk( true );
2052 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2057 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2058 $msgtext = ContentHandler
::getContentText( $content ); #XXX: could skip pseudo-messages like js/css here, based on content model.
2059 if ( $msgtext === false ||
$msgtext === null ) $msgtext = '';
2061 MessageCache
::singleton()->replace( $shortTitle, $msgtext );
2064 if( $options['created'] ) {
2065 self
::onArticleCreate( $this->mTitle
);
2067 self
::onArticleEdit( $this->mTitle
);
2070 wfProfileOut( __METHOD__
);
2074 * Edit an article without doing all that other stuff
2075 * The article must already exist; link tables etc
2076 * are not updated, caches are not flushed.
2078 * @param $text String: text submitted
2079 * @param $user User The relevant user
2080 * @param $comment String: comment submitted
2081 * @param $minor Boolean: whereas it's a minor modification
2083 * @deprecated since 1.WD, use doEditContent() instead.
2085 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
2086 wfDeprecated( __METHOD__
, "1.WD" );
2088 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
2089 return $this->doQuickEditContent( $content, $user, $comment , $minor );
2093 * Edit an article without doing all that other stuff
2094 * The article must already exist; link tables etc
2095 * are not updated, caches are not flushed.
2097 * @param $content Content: content submitted
2098 * @param $user User The relevant user
2099 * @param $comment String: comment submitted
2100 * @param $serialisation_format String: format for storing the content in the database
2101 * @param $minor Boolean: whereas it's a minor modification
2103 public function doQuickEditContent( Content
$content, User
$user, $comment = '', $minor = 0, $serialisation_format = null ) {
2104 wfProfileIn( __METHOD__
);
2106 $serialized = $content->serialize( $serialisation_format );
2108 $dbw = wfGetDB( DB_MASTER
);
2109 $revision = new Revision( array(
2110 'page' => $this->getId(),
2111 'text' => $serialized,
2112 'length' => $content->getSize(),
2113 'comment' => $comment,
2114 'minor_edit' => $minor ?
1 : 0,
2115 ) ); #XXX: set the content object
2116 $revision->insertOn( $dbw );
2117 $this->updateRevisionOn( $dbw, $revision );
2119 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2121 wfProfileOut( __METHOD__
);
2125 * Update the article's restriction field, and leave a log entry.
2126 * This works for protection both existing and non-existing pages.
2128 * @param $limit Array: set of restriction keys
2129 * @param $reason String
2130 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2131 * @param $expiry Array: per restriction type expiration
2132 * @param $user User The user updating the restrictions
2135 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
2138 if ( wfReadOnly() ) {
2139 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
2142 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2144 $id = $this->mTitle
->getArticleID();
2150 // Take this opportunity to purge out expired restrictions
2151 Title
::purgeExpiredRestrictions();
2153 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2154 # we expect a single selection, but the schema allows otherwise.
2155 $isProtected = false;
2159 $dbw = wfGetDB( DB_MASTER
);
2161 foreach ( $restrictionTypes as $action ) {
2162 if ( !isset( $expiry[$action] ) ) {
2163 $expiry[$action] = $dbw->getInfinity();
2165 if ( !isset( $limit[$action] ) ) {
2166 $limit[$action] = '';
2167 } elseif ( $limit[$action] != '' ) {
2171 # Get current restrictions on $action
2172 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2173 if ( $current != '' ) {
2174 $isProtected = true;
2177 if ( $limit[$action] != $current ) {
2179 } elseif ( $limit[$action] != '' ) {
2180 # Only check expiry change if the action is actually being
2181 # protected, since expiry does nothing on an not-protected
2183 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2189 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2193 # If nothing's changed, do nothing
2195 return Status
::newGood();
2198 if ( !$protect ) { # No protection at all means unprotection
2199 $revCommentMsg = 'unprotectedarticle';
2200 $logAction = 'unprotect';
2201 } elseif ( $isProtected ) {
2202 $revCommentMsg = 'modifiedarticleprotection';
2203 $logAction = 'modify';
2205 $revCommentMsg = 'protectedarticle';
2206 $logAction = 'protect';
2209 $encodedExpiry = array();
2210 $protectDescription = '';
2211 foreach ( $limit as $action => $restrictions ) {
2212 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
2213 if ( $restrictions != '' ) {
2214 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
2215 if ( $encodedExpiry[$action] != 'infinity' ) {
2216 $protectDescription .= wfMsgForContent( 'protect-expiring',
2217 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2218 $wgContLang->date( $expiry[$action], false, false ) ,
2219 $wgContLang->time( $expiry[$action], false, false ) );
2221 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
2224 $protectDescription .= ') ';
2227 $protectDescription = trim( $protectDescription );
2229 if ( $id ) { # Protection of existing page
2230 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2231 return Status
::newGood();
2234 # Only restrictions with the 'protect' right can cascade...
2235 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2236 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2238 # The schema allows multiple restrictions
2239 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
2243 # Update restrictions table
2244 foreach ( $limit as $action => $restrictions ) {
2245 if ( $restrictions != '' ) {
2246 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2247 array( 'pr_page' => $id,
2248 'pr_type' => $action,
2249 'pr_level' => $restrictions,
2250 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2251 'pr_expiry' => $encodedExpiry[$action]
2256 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2257 'pr_type' => $action ), __METHOD__
);
2261 # Prepare a null revision to be added to the history
2262 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle
->getPrefixedText() ) );
2264 $editComment .= ": $reason";
2266 if ( $protectDescription ) {
2267 $editComment .= " ($protectDescription)";
2270 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2273 # Insert a null revision
2274 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2275 $nullRevId = $nullRevision->insertOn( $dbw );
2277 $latest = $this->getLatest();
2278 # Update page record
2279 $dbw->update( 'page',
2281 'page_touched' => $dbw->timestamp(),
2282 'page_restrictions' => '',
2283 'page_latest' => $nullRevId
2284 ), array( /* WHERE */
2289 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2290 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2291 } else { # Protection of non-existing page (also known as "title protection")
2292 # Cascade protection is meaningless in this case
2295 if ( $limit['create'] != '' ) {
2296 $dbw->replace( 'protected_titles',
2297 array( array( 'pt_namespace', 'pt_title' ) ),
2299 'pt_namespace' => $this->mTitle
->getNamespace(),
2300 'pt_title' => $this->mTitle
->getDBkey(),
2301 'pt_create_perm' => $limit['create'],
2302 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
2303 'pt_expiry' => $encodedExpiry['create'],
2304 'pt_user' => $user->getId(),
2305 'pt_reason' => $reason,
2309 $dbw->delete( 'protected_titles',
2311 'pt_namespace' => $this->mTitle
->getNamespace(),
2312 'pt_title' => $this->mTitle
->getDBkey()
2318 $this->mTitle
->flushRestrictions();
2320 if ( $logAction == 'unprotect' ) {
2321 $logParams = array();
2323 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
2326 # Update the protection log
2327 $log = new LogPage( 'protect' );
2328 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
2330 return Status
::newGood();
2334 * Take an array of page restrictions and flatten it to a string
2335 * suitable for insertion into the page_restrictions field.
2336 * @param $limit Array
2339 protected static function flattenRestrictions( $limit ) {
2340 if ( !is_array( $limit ) ) {
2341 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2347 foreach ( $limit as $action => $restrictions ) {
2348 if ( $restrictions != '' ) {
2349 $bits[] = "$action=$restrictions";
2353 return implode( ':', $bits );
2357 * Same as doDeleteArticleReal(), but returns more detailed success/failure status
2358 * Deletes the article with database consistency, writes logs, purges caches
2360 * @param $reason string delete reason for deletion log
2361 * @param $suppress int bitfield
2362 * Revision::DELETED_TEXT
2363 * Revision::DELETED_COMMENT
2364 * Revision::DELETED_USER
2365 * Revision::DELETED_RESTRICTED
2366 * @param $id int article ID
2367 * @param $commit boolean defaults to true, triggers transaction end
2368 * @param &$error Array of errors to append to
2369 * @param $user User The deleting user
2370 * @return boolean true if successful
2372 public function doDeleteArticle(
2373 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2375 return $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user )
2376 == WikiPage
::DELETE_SUCCESS
;
2380 * Back-end article deletion
2381 * Deletes the article with database consistency, writes logs, purges caches
2383 * @param $reason string delete reason for deletion log
2384 * @param $suppress int bitfield
2385 * Revision::DELETED_TEXT
2386 * Revision::DELETED_COMMENT
2387 * Revision::DELETED_USER
2388 * Revision::DELETED_RESTRICTED
2389 * @param $id int article ID
2390 * @param $commit boolean defaults to true, triggers transaction end
2391 * @param &$error Array of errors to append to
2392 * @param $user User The deleting user
2393 * @return int: One of WikiPage::DELETE_* constants
2395 public function doDeleteArticleReal(
2396 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2398 global $wgUser, $wgContentHandlerUseDB;
2400 wfDebug( __METHOD__
. "\n" );
2402 if ( $this->mTitle
->getDBkey() === '' ) {
2403 return WikiPage
::DELETE_NO_PAGE
;
2406 $user = is_null( $user ) ?
$wgUser : $user;
2407 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
2408 return WikiPage
::DELETE_HOOK_ABORTED
;
2412 $this->loadPageData( 'forupdate' );
2413 $id = $this->getID();
2415 return WikiPage
::DELETE_NO_PAGE
;
2419 // Bitfields to further suppress the content
2422 // This should be 15...
2423 $bitfield |
= Revision
::DELETED_TEXT
;
2424 $bitfield |
= Revision
::DELETED_COMMENT
;
2425 $bitfield |
= Revision
::DELETED_USER
;
2426 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2428 $bitfield = 'rev_deleted';
2431 // we need to remember the old content so we can use it to generate all deletion updates.
2432 $content = $this->getContent( Revision
::RAW
);
2434 $dbw = wfGetDB( DB_MASTER
);
2435 $dbw->begin( __METHOD__
);
2436 // For now, shunt the revision data into the archive table.
2437 // Text is *not* removed from the text table; bulk storage
2438 // is left intact to avoid breaking block-compression or
2439 // immutable storage schemes.
2441 // For backwards compatibility, note that some older archive
2442 // table entries will have ar_text and ar_flags fields still.
2444 // In the future, we may keep revisions and mark them with
2445 // the rev_deleted field, which is reserved for this purpose.
2448 'ar_namespace' => 'page_namespace',
2449 'ar_title' => 'page_title',
2450 'ar_comment' => 'rev_comment',
2451 'ar_user' => 'rev_user',
2452 'ar_user_text' => 'rev_user_text',
2453 'ar_timestamp' => 'rev_timestamp',
2454 'ar_minor_edit' => 'rev_minor_edit',
2455 'ar_rev_id' => 'rev_id',
2456 'ar_parent_id' => 'rev_parent_id',
2457 'ar_text_id' => 'rev_text_id',
2458 'ar_text' => '\'\'', // Be explicit to appease
2459 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2460 'ar_len' => 'rev_len',
2461 'ar_page_id' => 'page_id',
2462 'ar_deleted' => $bitfield,
2463 'ar_sha1' => 'rev_sha1',
2466 if ( $wgContentHandlerUseDB ) {
2467 $row[ 'ar_content_model' ] = 'rev_content_model';
2468 $row[ 'ar_content_format' ] = 'rev_content_format';
2471 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2475 'page_id = rev_page'
2479 # Now that it's safely backed up, delete it
2480 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2481 $ok = ( $dbw->affectedRows() > 0 ); // getArticleID() uses slave, could be laggy
2484 $dbw->rollback( __METHOD__
);
2485 return WikiPage
::DELETE_NO_REVISIONS
;
2488 $this->doDeleteUpdates( $id, $content );
2490 # Log the deletion, if the page was suppressed, log it at Oversight instead
2491 $logtype = $suppress ?
'suppress' : 'delete';
2493 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2494 $logEntry->setPerformer( $user );
2495 $logEntry->setTarget( $this->mTitle
);
2496 $logEntry->setComment( $reason );
2497 $logid = $logEntry->insert();
2498 $logEntry->publish( $logid );
2501 $dbw->commit( __METHOD__
);
2504 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2505 return WikiPage
::DELETE_SUCCESS
;
2509 * Do some database updates after deletion
2511 * @param $id Int: page_id value of the page being deleted (B/C, currently unused)
2512 * @param $content Content: optional page content to be used when determining the required updates.
2513 * This may be needed because $this->getContent() may already return null when the page proper was deleted.
2515 public function doDeleteUpdates( $id, Content
$content = null ) {
2516 # update site status
2517 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2519 # remove secondary indexes, etc
2520 $updates = $this->getDeletionUpdates( $content );
2521 DataUpdate
::runUpdates( $updates );
2524 WikiPage
::onArticleDelete( $this->mTitle
);
2529 # Clear the cached article id so the interface doesn't act like we exist
2530 $this->mTitle
->resetArticleID( 0 );
2534 * Roll back the most recent consecutive set of edits to a page
2535 * from the same user; fails if there are no eligible edits to
2536 * roll back to, e.g. user is the sole contributor. This function
2537 * performs permissions checks on $user, then calls commitRollback()
2538 * to do the dirty work
2540 * @todo: seperate the business/permission stuff out from backend code
2542 * @param $fromP String: Name of the user whose edits to rollback.
2543 * @param $summary String: Custom summary. Set to default summary if empty.
2544 * @param $token String: Rollback token.
2545 * @param $bot Boolean: If true, mark all reverted edits as bot.
2547 * @param $resultDetails Array: contains result-specific array of additional values
2548 * 'alreadyrolled' : 'current' (rev)
2549 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2551 * @param $user User The user performing the rollback
2552 * @return array of errors, each error formatted as
2553 * array(messagekey, param1, param2, ...).
2554 * On success, the array is empty. This array can also be passed to
2555 * OutputPage::showPermissionsErrorPage().
2557 public function doRollback(
2558 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2560 $resultDetails = null;
2563 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2564 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2565 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2567 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2568 $errors[] = array( 'sessionfailure' );
2571 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2572 $errors[] = array( 'actionthrottledtext' );
2575 # If there were errors, bail out now
2576 if ( !empty( $errors ) ) {
2580 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2584 * Backend implementation of doRollback(), please refer there for parameter
2585 * and return value documentation
2587 * NOTE: This function does NOT check ANY permissions, it just commits the
2588 * rollback to the DB. Therefore, you should only call this function direct-
2589 * ly if you want to use custom permissions checks. If you don't, use
2590 * doRollback() instead.
2591 * @param $fromP String: Name of the user whose edits to rollback.
2592 * @param $summary String: Custom summary. Set to default summary if empty.
2593 * @param $bot Boolean: If true, mark all reverted edits as bot.
2595 * @param $resultDetails Array: contains result-specific array of additional values
2596 * @param $guser User The user performing the rollback
2599 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2600 global $wgUseRCPatrol, $wgContLang;
2602 $dbw = wfGetDB( DB_MASTER
);
2604 if ( wfReadOnly() ) {
2605 return array( array( 'readonlytext' ) );
2608 # Get the last editor
2609 $current = $this->getRevision();
2610 if ( is_null( $current ) ) {
2611 # Something wrong... no page?
2612 return array( array( 'notanarticle' ) );
2615 $from = str_replace( '_', ' ', $fromP );
2616 # User name given should match up with the top revision.
2617 # If the user was deleted then $from should be empty.
2618 if ( $from != $current->getUserText() ) {
2619 $resultDetails = array( 'current' => $current );
2620 return array( array( 'alreadyrolled',
2621 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2622 htmlspecialchars( $fromP ),
2623 htmlspecialchars( $current->getUserText() )
2627 # Get the last edit not by this guy...
2628 # Note: these may not be public values
2629 $user = intval( $current->getRawUser() );
2630 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2631 $s = $dbw->selectRow( 'revision',
2632 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2633 array( 'rev_page' => $current->getPage(),
2634 "rev_user != {$user} OR rev_user_text != {$user_text}"
2636 array( 'USE INDEX' => 'page_timestamp',
2637 'ORDER BY' => 'rev_timestamp DESC' )
2639 if ( $s === false ) {
2640 # No one else ever edited this page
2641 return array( array( 'cantrollback' ) );
2642 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2643 # Only admins can see this text
2644 return array( array( 'notvisiblerev' ) );
2648 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2649 # Mark all reverted edits as bot
2653 if ( $wgUseRCPatrol ) {
2654 # Mark all reverted edits as patrolled
2655 $set['rc_patrolled'] = 1;
2658 if ( count( $set ) ) {
2659 $dbw->update( 'recentchanges', $set,
2661 'rc_cur_id' => $current->getPage(),
2662 'rc_user_text' => $current->getUserText(),
2663 "rc_timestamp > '{$s->rev_timestamp}'",
2668 # Generate the edit summary if necessary
2669 $target = Revision
::newFromId( $s->rev_id
);
2670 if ( empty( $summary ) ) {
2671 if ( $from == '' ) { // no public user name
2672 $summary = wfMsgForContent( 'revertpage-nouser' );
2674 $summary = wfMsgForContent( 'revertpage' );
2678 # Allow the custom summary to use the same args as the default message
2680 $target->getUserText(), $from, $s->rev_id
,
2681 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2682 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2684 $summary = wfMsgReplaceArgs( $summary, $args );
2687 $flags = EDIT_UPDATE
;
2689 if ( $guser->isAllowed( 'minoredit' ) ) {
2690 $flags |
= EDIT_MINOR
;
2693 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2694 $flags |
= EDIT_FORCE_BOT
;
2697 # Actually store the edit
2698 $status = $this->doEditContent( $target->getContent(), $summary, $flags, $target->getId(), $guser );
2699 if ( !empty( $status->value
['revision'] ) ) {
2700 $revId = $status->value
['revision']->getId();
2705 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2707 $resultDetails = array(
2708 'summary' => $summary,
2709 'current' => $current,
2710 'target' => $target,
2718 * The onArticle*() functions are supposed to be a kind of hooks
2719 * which should be called whenever any of the specified actions
2722 * This is a good place to put code to clear caches, for instance.
2724 * This is called on page move and undelete, as well as edit
2726 * @param $title Title object
2728 public static function onArticleCreate( $title ) {
2729 # Update existence markers on article/talk tabs...
2730 if ( $title->isTalkPage() ) {
2731 $other = $title->getSubjectPage();
2733 $other = $title->getTalkPage();
2736 $other->invalidateCache();
2737 $other->purgeSquid();
2739 $title->touchLinks();
2740 $title->purgeSquid();
2741 $title->deleteTitleProtection();
2745 * Clears caches when article is deleted
2747 * @param $title Title
2749 public static function onArticleDelete( $title ) {
2750 # Update existence markers on article/talk tabs...
2751 if ( $title->isTalkPage() ) {
2752 $other = $title->getSubjectPage();
2754 $other = $title->getTalkPage();
2757 $other->invalidateCache();
2758 $other->purgeSquid();
2760 $title->touchLinks();
2761 $title->purgeSquid();
2764 HTMLFileCache
::clearFileCache( $title );
2767 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2768 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2772 if ( $title->getNamespace() == NS_FILE
) {
2773 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2774 $update->doUpdate();
2778 if ( $title->getNamespace() == NS_USER_TALK
) {
2779 $user = User
::newFromName( $title->getText(), false );
2781 $user->setNewtalk( false );
2786 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2790 * Purge caches on page update etc
2792 * @param $title Title object
2793 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2795 public static function onArticleEdit( $title ) {
2796 // Invalidate caches of articles which include this page
2797 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2800 // Invalidate the caches of all pages which redirect here
2801 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2803 # Purge squid for this page only
2804 $title->purgeSquid();
2806 # Clear file cache for this page only
2807 HTMLFileCache
::clearFileCache( $title );
2813 * Returns a list of hidden categories this page is a member of.
2814 * Uses the page_props and categorylinks tables.
2816 * @return Array of Title objects
2818 public function getHiddenCategories() {
2820 $id = $this->mTitle
->getArticleID();
2826 $dbr = wfGetDB( DB_SLAVE
);
2827 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2829 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2830 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2833 if ( $res !== false ) {
2834 foreach ( $res as $row ) {
2835 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2843 * Return an applicable autosummary if one exists for the given edit.
2844 * @param $oldtext String|null: the previous text of the page.
2845 * @param $newtext String|null: The submitted text of the page.
2846 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2847 * @return string An appropriate autosummary, or an empty string.
2848 * @deprecated since 1.WD, use ContentHandler::getAutosummary() instead
2850 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2851 # NOTE: stub for backwards-compatibility. assumes the given text is wikitext. will break horribly if it isn't.
2853 wfDeprecated( __METHOD__
, '1.WD' );
2855 $handler = ContentHandler
::getForModelID( CONTENT_MODEL_WIKITEXT
);
2856 $oldContent = is_null( $oldtext ) ?
null : $handler->unserializeContent( $oldtext );
2857 $newContent = is_null( $newtext ) ?
null : $handler->unserializeContent( $newtext );
2859 return $handler->getAutosummary( $oldContent, $newContent, $flags );
2863 * Auto-generates a deletion reason
2865 * @param &$hasHistory Boolean: whether the page has a history
2866 * @return mixed String containing deletion reason or empty string, or boolean false
2867 * if no revision occurred
2868 * @deprecated since 1.WD, use ContentHandler::getAutoDeleteReason() instead
2870 public function getAutoDeleteReason( &$hasHistory ) {
2871 #NOTE: stub for backwards-compatibility.
2873 wfDeprecated( __METHOD__
, '1.WD' );
2875 $handler = ContentHandler
::getForTitle( $this->getTitle() );
2876 return $handler->getAutoDeleteReason( $this->getTitle(), $hasHistory );
2880 * Update all the appropriate counts in the category table, given that
2881 * we've added the categories $added and deleted the categories $deleted.
2883 * @param $added array The names of categories that were added
2884 * @param $deleted array The names of categories that were deleted
2886 public function updateCategoryCounts( $added, $deleted ) {
2887 $ns = $this->mTitle
->getNamespace();
2888 $dbw = wfGetDB( DB_MASTER
);
2890 # First make sure the rows exist. If one of the "deleted" ones didn't
2891 # exist, we might legitimately not create it, but it's simpler to just
2892 # create it and then give it a negative value, since the value is bogus
2895 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2896 $insertCats = array_merge( $added, $deleted );
2897 if ( !$insertCats ) {
2898 # Okay, nothing to do
2902 $insertRows = array();
2904 foreach ( $insertCats as $cat ) {
2905 $insertRows[] = array(
2906 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2910 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2912 $addFields = array( 'cat_pages = cat_pages + 1' );
2913 $removeFields = array( 'cat_pages = cat_pages - 1' );
2915 if ( $ns == NS_CATEGORY
) {
2916 $addFields[] = 'cat_subcats = cat_subcats + 1';
2917 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2918 } elseif ( $ns == NS_FILE
) {
2919 $addFields[] = 'cat_files = cat_files + 1';
2920 $removeFields[] = 'cat_files = cat_files - 1';
2927 array( 'cat_title' => $added ),
2936 array( 'cat_title' => $deleted ),
2943 * Updates cascading protections
2945 * @param $parserOutput ParserOutput object for the current version
2947 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2948 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2952 // templatelinks table may have become out of sync,
2953 // especially if using variable-based transclusions.
2954 // For paranoia, check if things have changed and if
2955 // so apply updates to the database. This will ensure
2956 // that cascaded protections apply as soon as the changes
2959 # Get templates from templatelinks
2960 $id = $this->mTitle
->getArticleID();
2962 $tlTemplates = array();
2964 $dbr = wfGetDB( DB_SLAVE
);
2965 $res = $dbr->select( array( 'templatelinks' ),
2966 array( 'tl_namespace', 'tl_title' ),
2967 array( 'tl_from' => $id ),
2971 foreach ( $res as $row ) {
2972 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2975 # Get templates from parser output.
2976 $poTemplates = array();
2977 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2978 foreach ( $templates as $dbk => $id ) {
2979 $poTemplates["$ns:$dbk"] = true;
2984 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2986 if ( count( $templates_diff ) > 0 ) {
2987 # Whee, link updates time.
2988 # Note: we are only interested in links here. We don't need to get other DataUpdate items from the parser output.
2989 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2995 * Return a list of templates used by this article.
2996 * Uses the templatelinks table
2998 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
2999 * @return Array of Title objects
3001 public function getUsedTemplates() {
3002 return $this->mTitle
->getTemplateLinksFrom();
3006 * Perform article updates on a special page creation.
3008 * @param $rev Revision object
3010 * @todo This is a shitty interface function. Kill it and replace the
3011 * other shitty functions like doEditUpdates and such so it's not needed
3013 * @deprecated since 1.18, use doEditUpdates()
3015 public function createUpdates( $rev ) {
3016 wfDeprecated( __METHOD__
, '1.18' );
3018 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
3022 * This function is called right before saving the wikitext,
3023 * so we can do things like signatures and links-in-context.
3025 * @deprecated in 1.19; use Parser::preSaveTransform() instead
3026 * @param $text String article contents
3027 * @param $user User object: user doing the edit
3028 * @param $popts ParserOptions object: parser options, default options for
3029 * the user loaded if null given
3030 * @return string article contents with altered wikitext markup (signatures
3031 * converted, {{subst:}}, templates, etc.)
3033 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
3034 global $wgParser, $wgUser;
3036 wfDeprecated( __METHOD__
, '1.19' );
3038 $user = is_null( $user ) ?
$wgUser : $user;
3040 if ( $popts === null ) {
3041 $popts = ParserOptions
::newFromUser( $user );
3044 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
3048 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3050 * @deprecated in 1.19; use Title::isBigDeletion() instead.
3053 public function isBigDeletion() {
3054 wfDeprecated( __METHOD__
, '1.19' );
3055 return $this->mTitle
->isBigDeletion();
3059 * Get the approximate revision count of this page.
3061 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
3064 public function estimateRevisionCount() {
3065 wfDeprecated( __METHOD__
, '1.19' );
3066 return $this->mTitle
->estimateRevisionCount();
3070 * Update the article's restriction field, and leave a log entry.
3072 * @deprecated since 1.19
3073 * @param $limit Array: set of restriction keys
3074 * @param $reason String
3075 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
3076 * @param $expiry Array: per restriction type expiration
3077 * @param $user User The user updating the restrictions
3078 * @return bool true on success
3080 public function updateRestrictions(
3081 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
3085 $user = is_null( $user ) ?
$wgUser : $user;
3087 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
3091 * @deprecated since 1.18
3093 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3094 wfDeprecated( __METHOD__
, '1.18' );
3096 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
3100 * @deprecated since 1.18
3102 public function viewUpdates() {
3103 wfDeprecated( __METHOD__
, '1.18' );
3105 return $this->doViewUpdates( $wgUser );
3109 * @deprecated since 1.18
3112 public function useParserCache( $oldid ) {
3113 wfDeprecated( __METHOD__
, '1.18' );
3115 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
3119 * Returns a list of updates to be performed when this page is deleted. The updates should remove any infomration
3120 * about this page from secondary data stores such as links tables.
3122 * @param Content|null $content optional Content object for determining the necessary updates
3123 * @return Array an array of DataUpdates objects
3125 public function getDeletionUpdates( Content
$content = null ) {
3127 // load content object, which may be used to determine the necessary updates
3128 // XXX: the content may not be needed to determine the updates, then this would be overhead.
3129 $content = $this->getContent( Revision
::RAW
);
3132 $updates = $this->getContentHandler()->getDeletionUpdates( $content, $this->mTitle
);
3134 wfRunHooks( 'WikiPageDeletionUpdates', array( $this, &$updates ) );
3140 class PoolWorkArticleView
extends PoolCounterWork
{
3158 * @var ParserOptions
3160 private $parserOptions;
3165 private $content = null;
3168 * @var ParserOutput|bool
3170 private $parserOutput = false;
3175 private $isDirty = false;
3180 private $error = false;
3186 * @param $revid Integer: ID of the revision being parsed
3187 * @param $useParserCache Boolean: whether to use the parser cache
3188 * @param $parserOptions parserOptions to use for the parse operation
3189 * @param $content Content|String: content to parse or null to load it; may also be given as a wikitext string, for BC
3191 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $content = null ) {
3192 if ( is_string($content) ) { #BC: old style call
3193 $modelId = $page->getRevision()->getContentModel();
3194 $format = $page->getRevision()->getContentFormat();
3195 $content = ContentHandler
::makeContent( $content, $page->getTitle(), $modelId, $format );
3198 $this->page
= $page;
3199 $this->revid
= $revid;
3200 $this->cacheable
= $useParserCache;
3201 $this->parserOptions
= $parserOptions;
3202 $this->content
= $content;
3203 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
3204 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
3208 * Get the ParserOutput from this object, or false in case of failure
3210 * @return ParserOutput
3212 public function getParserOutput() {
3213 return $this->parserOutput
;
3217 * Get whether the ParserOutput is a dirty one (i.e. expired)
3221 public function getIsDirty() {
3222 return $this->isDirty
;
3226 * Get a Status object in case of error or false otherwise
3228 * @return Status|bool
3230 public function getError() {
3231 return $this->error
;
3238 global $wgUseFileCache;
3240 // @todo: several of the methods called on $this->page are not declared in Page, but present in WikiPage and delegated by Article.
3242 $isCurrent = $this->revid
=== $this->page
->getLatest();
3244 if ( $this->content
!== null ) {
3245 $content = $this->content
;
3246 } elseif ( $isCurrent ) {
3247 $content = $this->page
->getContent( Revision
::RAW
); #XXX: why use RAW audience here, and PUBLIC (default) below?
3249 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
3250 if ( $rev === null ) {
3253 $content = $rev->getContent(); #XXX: why use PUBLIC audience here (default), and RAW above?
3256 $time = - microtime( true );
3257 // TODO: page might not have this method? Hard to tell what page is supposed to be here...
3258 $this->parserOutput
= $content->getParserOutput( $this->page
->getTitle(), $this->revid
, $this->parserOptions
);
3259 $time +
= microtime( true );
3263 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3264 $this->page
->getTitle()->getPrefixedDBkey() ) );
3267 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
3268 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
3271 // Make sure file cache is not used on uncacheable content.
3272 // Output that has magic words in it can still use the parser cache
3273 // (if enabled), though it will generally expire sooner.
3274 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
3275 $wgUseFileCache = false;
3279 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
3288 function getCachedWork() {
3289 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
3291 if ( $this->parserOutput
=== false ) {
3292 wfDebug( __METHOD__
. ": parser cache miss\n" );
3295 wfDebug( __METHOD__
. ": parser cache hit\n" );
3303 function fallback() {
3304 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
3306 if ( $this->parserOutput
=== false ) {
3307 wfDebugLog( 'dirty', "dirty missing\n" );
3308 wfDebug( __METHOD__
. ": no dirty cache\n" );
3311 wfDebug( __METHOD__
. ": sending dirty output\n" );
3312 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
3313 $this->isDirty
= true;
3319 * @param $status Status
3322 function error( $status ) {
3323 $this->error
= $status;